import { mapState } from "vuex";
import Vue from "vue";
import store from "@/store";
import { chineseToInitials } from "@/util/pinyin";

// 尝试将用户在根目录中的store/index.js的vuex的state变量，全部加载到全局变量中
let $uStoreKey = [];
try {
  $uStoreKey = store.state ? Object.keys(store.state) : [];
} catch (e) {}

module.exports = {
  created() {
    // 将vuex方法挂在到$u中
    // 使用方法为：如果要修改vuex的state中的user.name变量为"史诗" => this.$u.vuex('user.name', '史诗')
    // 如果要修改vuex的state的version变量为1.0.1 => this.$u.vuex('version', '1.0.1')
    this.$u.vuex = (name, value) => {
      this.$store.commit("$uStore", {
        name,
        value,
      });
    };

    this.$u.networkSuccess = async (type) =>{
      this.$store.commit("$uStore", {
        name: "vuex_networkSuccess",
        value: type,
      });
    }

    this.$u.vuex_set_current_group = (data) => {
      this.$store.commit("$uStore", {
        name: "vuex_current_group",
        value: data,
      });
      return data;
    };
    
    this.$u.vuex_current_group = async (id) => {
      const res = await Vue.prototype.$u.api.chatGroup.getChatGroupInfo({ id });
      this.$store.commit("$uStore", {
        name: "vuex_current_group",
        value: res.data,
      });
      return res.data;
    };

    this.$u.vuex_userInfo = async (userInfo) => {
      const res = await Vue.prototype.$u.api.imUser.updateUserInfo(userInfo);
      if (res.code !== 200) return;
      this.$store.commit("$uStore", {
        name: "vuex_userInfo",
        value: res.data,
      });
      return res.data;
    };

    this.$u.refreshContactList = async () => {
      const res = await Vue.prototype.$u.api.imUser.getMyFriendList({});
      const list = res.data;
      const frObj = {};
      list.map((s) => {
        const frUser = s.from_user_id === this.vuex_userInfo.id ? s.to_user : s.from_user;
        const userRemark = s.from_user_id === this.vuex_userInfo.id ? s.to_remark : s.from_remark;
        frUser.remark = userRemark || ''
        const aa = chineseToInitials(String(userRemark || frUser.name));
        if (frObj[aa[0]]) {
          frObj[aa[0]].push(frUser);
        } else {
          frObj[aa[0]] = [frUser];
        }
        return aa[0];
      });

      const ilist = Object.keys(frObj).sort()

      const frList = [];
      for (let n of ilist) {
        frList.push({
          firstLetter: n,
          friends: frObj[n],
        });
      }
      this.$store.commit("$uStore", {
        name: "vuex_contactListData",
        value: frList,
      });
      this.$store.commit("$uStore", {
        name: "vuex_contactOringinData",
        value: list,
      });
      this.$store.commit("$uStore", {
        name: "vuex_contactIndex",
        value: ilist,
      });
    };

    this.$u.refreshChatGroupList = async () => {
      const res = await Vue.prototype.$u.api.chatGroup.getMyChatGroupList({});
      if (res.code !== 200) return
      for (const item of res.data) {
        item.showOptionFlag=false;
        if (item.group.is_multi === 'PRIVATE') {
          const frReleations = JSON.parse(item.group.friend_relations)
          const myUserId = this.vuex_userInfo.id
          let findU
          const groupToUserId = myUserId === frReleations[0] ? frReleations[1] : frReleations[0]
          for (const o of this.vuex_contactOringinData) {
            if (groupToUserId === o.to_user_id) {
              findU = o.to_user
              break
            } else if (groupToUserId === o.from_user_id) {
              findU = o.from_user
              break
            }
          }
          if (findU) {
            item.group.cover = findU.avatar
            item.group.title = findU.remark || findU.name
          }
        }
        if (item.remark) item.group.title = item.remark
      }
      this.$store.commit("$uStore", {
        name: "vuex_groupList",
        value: res.data
      })
      return res.data
    }

    this.$u.logout = () => {
      this.$store.commit("$uStore", {
        name: "vuex_token",
        value: "",
      });
      uni.clearStorage()
      // #ifdef H5
      uni.reLaunch({
        url: "/pages/start/wx-login",
      });
      // #endif
      //#ifdef APP-PLUS
      plus.runtime.restart();
      //#endif
    };
  },
  computed: {
    // 将vuex的state中的所有变量，解构到全局混入的mixin中
    ...mapState($uStoreKey),
  },
};
